import ast
from application.db.mysql_db.nsfc.NsfcInfoAttachmentList import NsfcInfoAttachmentList
from application.db.mysql_db.nsfc.NsfcInfoSectionList import NsfcInfoSectionList
from application.utils.base_oss import BaseOss

# ===============================================================
# 本脚本主要用于：
# 1. 查询 NSFC（国家自然科学基金）项目数据库中的 Section 和 Attachment 信息；
# 2. 从存储字段中提取 OSS（对象存储服务）文件路径信息；
# 3. 调用 BaseOss 工具类生成文件的可访问 URL；
# 4. 可根据需要将更新后的 URL 回写至数据库。
# ===============================================================

# =============================
# 查询数据库中的 Section 数据
# 条件：仅查询 section_attr 为 'figure' 的记录
# =============================
section_list = NsfcInfoSectionList.select().where(NsfcInfoSectionList.section_attr == 'figure')

# =============================
# 查询数据库中的 Attachment 数据
# =============================
attachment_list = NsfcInfoAttachmentList.select()

# ===============================================================
# 遍历 Section 数据
# ===============================================================
for section in section_list:
    media_info = section.media_info  # 读取字段 media_info，该字段一般为字符串形式的字典

    # 如果 media_info 为空，跳过当前循环
    if not media_info:
        continue

    # 使用 ast.literal_eval 将字符串安全地转换为 Python 字典对象
    media_info = ast.literal_eval(media_info)

    # 从 media_info 中提取 OSS 存储桶名和文件路径
    bucket = media_info.get('bucket_name')
    path = media_info.get('file_path')

    # 调用 BaseOss 工具类，生成该文件的访问 URL
    ret = BaseOss(bucket_name=bucket).generate_file_url(path)

    # 若返回结果中 result 字段为 False，表示生成失败，则跳过
    if not ret.get('result'):
        continue

    # 从返回结果中获取可访问的文件 URL
    file_url = ret.get('data')

    # 打印生成的文件 URL
    print(file_url)

    # =============================
    # 如需将新的 URL 写回数据库，可启用以下代码：
    # section.media_info = {"bucket_name":"xxxx","file_path":"xxxxxx"} 可能得转字符串
    # section.save()
    # =============================

# ===============================================================
# 遍历 Attachment 数据
# ===============================================================
for attachment in attachment_list:
    attachment_address = attachment.attachment_address  # 读取字段 attachment_address，该字段为字典或 JSON 结构

    # 如果地址字段为空，跳过当前循环
    if not attachment_address:
        continue

    # 从 attachment_address 中提取 OSS 存储桶名和文件路径
    bucket = attachment_address.get('bucket_name')
    path = attachment_address.get('file_path')

    # 调用 BaseOss 工具类生成可访问的文件 URL
    ret = BaseOss(bucket_name=bucket).generate_file_url(path)

    # 若返回失败，则跳过
    if not ret.get('result'):
        continue

    # 从返回结果中提取 URL
    file_url = ret.get('data')

    # 打印生成的文件 URL
    print(file_url)

    # =============================
    # 如需回写数据库，可启用以下代码：
    # attachment.attachment_address = {"bucket_name":"xxxx","file_path":"xxxxxx"}
    # attachment.save()
    # =============================
